package com.waimai.service;

import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import com.waimai.dao.RestaurantDao;
import com.waimai.model.Restaurant;

/**
 * 处理前台调用对数据库的查询
 * 
 * @author WEISHAOFEI
 * 
 */

@Repository("restaurantservice")
public class RestaurantService {

	@Resource(name = "restaurantdao")
	private RestaurantDao restaurantdao;

	/**
	 * 
	 * @param address
	 *            校内地址选择
	 * @param company
	 *            外卖网站
	 * @param drink
	 *            饮料
	 * @return 筛选后的饭店列表
	 */
	public List<Restaurant> getAllRestaurantByItems(String address,
			String company, String drink) {
		StringBuffer sql = new StringBuffer(
				"SELECT * FROM address a,rarelationship r,restaurant rs WHERE a.ID = r.AID AND r.rId= rs.id ");

		if (address != null && !address.equals("")) {
			sql.append(" AND a.address='" + address + "'");
		}
		if (company != null && !company.equals("")) {
			if (company.equals("美团")) {
				sql.append(" and rs.company=0");
			} else if (company.equals("饿了么")) {
				sql.append(" and rs.company=1");
			}
		}
		if (drink != null && !drink.equals("")) {
			sql.append(" and rs.drinklist like '%" + drink + "%'");
		}
		List<Restaurant> list = restaurantdao.getAllRestaurant(sql.toString());
		// list.toArray()
		Collections.sort(list, new RestaurantCompare());
		return list;
	}
}

class RestaurantCompare implements Comparator<Restaurant> {

	@Override
	public int compare(Restaurant o1, Restaurant o2) {
		// TODO Auto-generated method stub
		String price1 = o1.getmSaleList();
		String price2 = o2.getmSaleList();
		int discount1 = Integer.parseInt(price1.substring(4, 5));
		int discount2 = Integer.parseInt(price2.substring(4, 5));
		if (discount1 - discount2 > 0) {
			return -1;
		} else if (discount1 - discount2 < 0) {
			return 1;
		} else {
			return 0;
		}
	}

}
